import React from "react";
import {
  Row,
  Col,
  Input,
  Button,
  Spin,
  Modal,
  Space,
  Table,
  Tooltip,
  message,
  PageHeader,
  List,
  Tag,
  Divider,
  Drawer,
} from "antd";
import {
  EditFilled,
  HighlightOutlined,
  PieChartOutlined,
  CloudDownloadOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
// import "./stu.css";

import moment from "moment";
import FileViewer from "react-file-viewer";

import ExportJsonExcel from "js-export-excel";
import PieChart from "./piechart";

import { _getExpingStu, _updateStuMark } from "../../../../utils/exp/index";
const { Search } = Input;
const url = require("../../../../utils/conUrl");

class NewsList extends React.Component {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    isLoading: false,
    confirmLoading: false,
    stuList: null,

    stu_name: null,
    stu_num: null,
    stu_word: null,
    exp_data: null,
    exp_mark: null,
    sel_exp_id: null,
    is_correct: false,

    e_visible: false,
    pieChart_v: false,
    pieData: [],
  };
  UNSAFE_componentWillMount = () => {
    this.setState({ exp_data: this.props.location.state });
  };
  getData = () => {
    // console.log(this.props.location.state.exp_id);
    this.setState({ isLoading: true });
    _getExpingStu(this.props.location.state.exp_id)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          // console.log(res.data.data);
          this.setState({ isLoading: false });
          const stuList = res.data.data;
          for (let i = 0; i < stuList.length; i++) {
            stuList[i].key = stuList[i].stu_id;
            // stuList[i].stu_num = stuList[i].stu_num;
            // stuList[i].stu_name = stuList[i].stu_name;
            // stuList[i].stu_word = stuList[i].stu_word;
            // stuList[i].stu_data = stuList[i].stu_data;
            stuList[i].control = stuList[i].sel_exp_id;
          }
          this.setState({ stuList: stuList });
          let pieData = [
            {
              type: "优秀",
              value: 0,
            },
            {
              type: "良",
              value: 0,
            },
            {
              type: "中",
              value: 0,
            },
            {
              type: "及格",
              value: 0,
            },
            {
              type: "不及格",
              value: 0,
            },
          ];
          stuList.map((v) => {
            let num = parseInt(v.exp_mark);
            num = parseInt(num / 10);
            switch (num) {
              case 10:
                pieData[0].value++;
                break;
              case 9:
                pieData[0].value++;
                break;
              case 8:
                pieData[1].value++;
                break;
              case 7:
                pieData[2].value++;
                break;
              case 6:
                pieData[3].value++;
                break;
              default:
                pieData[4].value++;
                break;
            }
          });
          //   console.log(pieData);
          this.setState({ pieData: pieData });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  componentDidMount = () => {
    this.getData();
  };
  editSource = (val) => {
    console.log(val);
    this.setState({
      stu_name: val.stu_name,
      stu_num: val.stu_num,
      stu_word: val.stu_word,
      exp_mark: val.exp_mark,
      sel_exp_id: val.sel_exp_id,
      e_visible: true,
    });
  };
  handleCancel = () => {
    this.setState({
      e_visible: false,
      a_visible: false,
      pieChart_v: false,
    });
  };
  onInputChange = (e) => {
    console.log(e.target.name);
    let inputValue = e.target.value;
    let inputName = e.target.name;
    this.setState({
      [inputName]: inputValue,
    });
  };

  viewPieChart = () => {
    this.setState({ pieChart_v: true });
  };
  //批改分数
  correctOnSearch = (val, mark) => {
    if (mark == "") {
      message.info("请输入分数");
      return;
    }
    this.setState({ confirmLoading: true });

    let temp = {
      exp_mark: mark,
    };
    console.log("search:", val, mark);
    _updateStuMark(val.sel_exp_id, temp)
      .then((res) => {
        if (res.status === 200) {
          message.success("批改成功");
          this.setState({ confirmLoading: false });
        }
      })
      .catch(() => {
        this.setState({ confirmLoading: false });
        message.error("服务器错误");
      });
  };
  //编辑修改分数
  correctOnSearch2 = (val) => {
    if (val == "") {
      message.info("请输入分数");
      return;
    }
    this.setState({ confirmLoading: true });
    let temp = {
      exp_mark: val,
    };
    _updateStuMark(this.state.sel_exp_id, temp)
      .then((res) => {
        if (res.status === 200) {
          message.success("批改成功");
          this.setState({ confirmLoading: false, e_visible: false });

          this.getData();
        }
      })
      .catch(() => {
        this.setState({ confirmLoading: false });
        message.error("服务器错误");
      });
  };
  //导出成绩
  downloadFileToExcel = () => {
    let dataTable = []; //excel文件中的数据内容
    let option = {}; //option代表的就是excel文件
    let date = moment().format("YYYY-MM-DD");
    dataTable = this.state.stuList; //从props中获取数据源
    option.fileName = `${date}-${this.state.exp_data.exp_name}-成绩`; //excel文件名称
    option.datas = [
      {
        sheetData: dataTable, //excel文件中的数据源
        sheetName: "学生", //excel文件中sheet页名称
        sheetFilter: ["stu_num", "stu_name", "exp_mark"], //excel文件中需显示的列数据
        sheetHeader: ["学号", "姓名", "成绩", "备注"], //excel文件中每列的表头名称
      },
    ];
    let toExcel = new ExportJsonExcel(option); //生成excel文件
    toExcel.saveExcel(); //下载excel文件
  };
  //批改
  correctHandle = () => {
    this.setState({ is_correct: true });
  };
  //返回学生页面
  backHandler = () => {
    this.setState({ is_correct: false });
    this.getData();
  };
  render() {
    let expData = this.state.exp_data;
    const columns = [
      {
        title: "学号",
        dataIndex: "stu_num",
      },
      {
        title: "姓名",
        dataIndex: "stu_name",
      },
      {
        title: "实验报告",
        dataIndex: "stu_word",
        render: (text) => (
          <>
            {text === null ? (
              <Tag color="magenta">未提交</Tag>
            ) : (
              <Tag>已提交</Tag>
            )}
          </>
        ),
      },
      {
        title: "实验成果",
        dataIndex: "stu_data",
        render: (text) => (
          <>
            {text === null ? (
              <Tag color="magenta">未提交</Tag>
            ) : (
              <Tag>已提交</Tag>
            )}
          </>
        ),
      },
      {
        title: "成绩",
        dataIndex: "exp_mark",
        defaultSortOrder: "descend",
        sorter: (a, b) => a.exp_mark - b.exp_mark,

        render: (text) => <>{!text ? <Tag color="blue">未批阅</Tag> : text}</>,
      },
      {
        title: "操作",
        dataIndex: "control",
        render: (text, record) => (
          <Space size="middle">
            <Tooltip placement="topLeft" title="批改">
              <EditFilled
                onClick={this.editSource.bind(this, record)}
                style={{ color: "#95a5a6" }}
              />
            </Tooltip>
            {!record.stu_word ? null : (
              <Tooltip placement="topLeft" title="下载报告">
                <Button
                  type="primary"
                  shape="circle"
                  icon={<DownloadOutlined />}
                  size="small"
                  href={url.api+"/file/word/" + record.stu_word}
                />
              </Tooltip>
            )}

            {!record.stu_data ? null : (
              <Tooltip placement="topLeft" title="下载附件">
                <Button
                  type="dashed"
                  shape="circle"
                  icon={<DownloadOutlined />}
                  size="small"
                  href={url.api+"/file/fj/" + record.stu_data}
                />
              </Tooltip>
            )}
          </Space>
        ),
      },
    ];

    return (
      <div>
      
        {this.state.is_correct ? (
          <div>
            <PageHeader
              className="site-page-header"
              onBack={this.backHandler}
              title={"批改报告"}
              subTitle={expData.exp_time}
            />
            <div className="admin-body" style={{ padding: 15, minHeight: 360 }}>
              <Spin tip="Loading..." spinning={this.state.isLoading}>
                <List
                  bordered
                  dataSource={this.state.stuList}
                  pagination={{
                    onChange: (page) => {
                      console.log(page);
                    },
                    pageSize: 1,
                    position: "top",
                  }}
                  renderItem={(v) => (
                    <List.Item key={v}>
                      <Row>
                        <Col span={24}>
                          <Row>
                            <Col span={12}>
                              <Space>
                                {v.stu_num}
                                {v.stu_name}
                                {!v.stu_word ? (
                                  <Tag color="magenta">未交报告</Tag>
                                ) : null}
                                {v.exp_mark == "" ? (
                                  <Tag color="blue">未批阅</Tag>
                                ) : (
                                  <Tag>已批阅</Tag>
                                )}
                              </Space>
                            </Col>
                            <Col span={6} offset={6}>
                              <Search
                                placeholder="输入你要给的分数"
                                onSearch={this.correctOnSearch.bind(this, v)}
                                enterButton="确认"
                                defaultValue={v.exp_mark}
                                loading={this.state.confirmLoading}
                              />
                            </Col>
                          </Row>
                        </Col>
                        <Divider>实验报告</Divider>
                        <Col span={24}>
                          {!v.stu_word ? (
                            <h1 style={{ color: "#ff7675" }}>
                              该同学未提交实验报告
                            </h1>
                          ) : (
                            <FileViewer
                              fileType="docx"
                              filePath={"/file/word/" + v.stu_word}
                              onError={this.onError}
                              errorComponent={Error}
                              unsupportedComponent={Error}
                            />
                          )}
                        </Col>
                      </Row>
                    </List.Item>
                  )}
                />
              </Spin>
            </div>
          </div>
        ) : (
          <div>
            <PageHeader
              className="site-page-header"
              onBack={() => window.history.back()}
              title={expData.exp_name}
              subTitle={expData.exp_time}
              extra={[
                <Button
                  key="1"
                  icon={<PieChartOutlined />}
                  type="primary"
                  onClick={this.viewPieChart}
                >
                  成绩统计
                </Button>,
                <Modal
                  title={
                    expData.exp_name + "-" + expData.exp_class + "-成绩统计"
                  }
                  visible={this.state.pieChart_v}
                  onCancel={this.handleCancel}
                >
                  <PieChart data={this.state.pieData} />
                </Modal>,
                <Button
                  key="2"
                  icon={<HighlightOutlined />}
                  type="primary"
                  onClick={this.correctHandle}
                >
                  批阅
                </Button>,
                <Button
                  icon={<CloudDownloadOutlined />}
                  onClick={this.downloadFileToExcel}
                  type="primary"
                  key="3"
                >
                  导出成绩
                </Button>,
              ]}
            />
            <div className="admin-body" style={{ padding: 15, minHeight: 360 }}>
              <Spin tip="Loading..." spinning={this.state.isLoading}>
                <Table
                  columns={columns}
                  dataSource={this.state.stuList}
                  // rowSelection={rowSelection}
                  pagination={{ pageSize: 10 }}
                  // scroll={{ y: 300 }}
                />
              </Spin>
              <Drawer
                title={
                  <Space size="large">
                    <div>{this.state.stu_num + "-" + this.state.stu_name}</div>
                    <Search
                      placeholder="输入你要给的分数"
                      onSearch={this.correctOnSearch2}
                      enterButton="确认"
                      loading={this.state.confirmLoading}
                    />
                    <div>分数：{this.state.exp_mark}</div>
                  </Space>
                }
                placement="left"
                closable={false}
                onClose={this.handleCancel}
                visible={this.state.e_visible}
                key="left"
                width={"70vw"}
              >
                {!this.state.stu_word ? (
                  <h1 style={{ color: "#ff7675" }}>该同学未提交实验报告</h1>
                ) : (
                  <FileViewer
                    fileType="docx"
                    filePath={"/file/word/" + this.state.stu_word}
                    onError={this.onError}
                    errorComponent={Error}
                    unsupportedComponent={Error}
                  />
                )}
              </Drawer>
            </div>
          </div>
        )}
      </div>
    );
  }
}

export default NewsList;
